using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Windows;
using DrawerMenu.Services;
using DrawerMenu.ViewModels;
using DrawerMenu.Views;

namespace DrawerMenu;

public partial class App : Application
{
    private readonly IHost _host;

    public App()
    {
        var builder = Host.CreateApplicationBuilder();

        // 注册导航服务
        builder.Services.AddSingleton<INavigationService>(provider =>
        {
            var navService = new NavigationService(provider);
            navService.RegisterMapping<HomeViewModel, HomePage>();
            navService.RegisterMapping<ProfileViewModel, ProfilePage>();
            navService.RegisterMapping<SettingsViewModel, SettingsPage>();
            navService.RegisterMapping<AboutViewModel, AboutPage>();
            return navService;
        });

        // 注册ViewModels
        builder.Services.AddSingleton<MainViewModel>();
        builder.Services.AddTransient<HomeViewModel>();
        builder.Services.AddTransient<ProfileViewModel>();
        builder.Services.AddTransient<SettingsViewModel>();
        builder.Services.AddTransient<AboutViewModel>();

        // 注册Views
        builder.Services.AddTransient<HomePage>();
        builder.Services.AddTransient<ProfilePage>();
        builder.Services.AddTransient<SettingsPage>();
        builder.Services.AddTransient<AboutPage>();

        // 注册主窗口
        builder.Services.AddSingleton<MainWindow>();

        _host = builder.Build();
    }

    protected override async void OnStartup(StartupEventArgs e)
    {
        // 显示启动页
        var splashWindow = new SplashWindow();
        splashWindow.Show();

        // 异步启动主机和加载资源
        await Task.Run(async () =>
        {
            await _host.StartAsync();
            
            // 模拟额外的初始化工作
            await Task.Delay(500);
        });

        // 启动页加载完成后的回调
        splashWindow.LoadingComplete += (s, args) =>
        {
            // 在UI线程上创建并显示主窗口
            Dispatcher.Invoke(() =>
            {
                var mainWindow = _host.Services.GetRequiredService<MainWindow>();
                var mainViewModel = _host.Services.GetRequiredService<MainViewModel>();
                mainWindow.DataContext = mainViewModel;
                
                // 默认导航到首页
                mainViewModel.NavigationService.NavigateTo<HomeViewModel>();
                
                // 显示主窗口
                mainWindow.Show();
                
                // 关闭启动页
                splashWindow.Close();
            });
        };

        base.OnStartup(e);
    }
    protected override async void OnExit(ExitEventArgs e)
    {
        await _host.StopAsync();
        _host.Dispose();
        base.OnExit(e);
    }
}
